package com.gmail.huxiaowi.cblog.dao.impl.jpa;

import java.lang.reflect.ParameterizedType;
import java.util.Collection;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import com.gmail.huxiaowi.cblog.dao.IGenericDao;

public abstract class GenericDaoJPAImpl<T> implements IGenericDao<T>{
    private EntityManager em = null;
    private Class<T> clazz = null;
    private String entityName = null;
    
    @SuppressWarnings("unchecked")
    public GenericDaoJPAImpl() {
       clazz = (Class<T>)((ParameterizedType) (this.getClass().getGenericSuperclass())).getActualTypeArguments()[0];
       entityName = clazz.getSimpleName();
    }
    
    public void delete(T t) {
        // TODO Auto-generated method stub
        em.remove(t);
    }

    public void insert(T t) {
        // TODO Auto-generated method stub
        em.persist(t);
    }

    /* (non-Javadoc)
     * @see com.gmail.huxiaowi.cblog.dao.GenericDao#listSize()
     */
    public long listSize() {
        return 0;
    }

    @SuppressWarnings("unchecked")
    public Collection<T> queryAll() {
        // TODO Auto-generated method stub
        Query qy = em.createQuery("select t from " + entityName + " t");
        return qy.getResultList();
    }

    public T queryById(Long id) {
        // TODO Auto-generated method stub
        return em.find(clazz, id);
    }

    public void update(T t) {
        // TODO Auto-generated method stub
        em.merge(t);
    }

    public EntityManager getEm() {
        return em;
    }

    @PersistenceContext
    public void setEm(EntityManager em) {
        this.em = em;
    }
}
